package com.doraemon.controller.admin;

import com.doraemon.constant.JwtClaimsConstant;
import com.doraemon.dto.EmployeeDTO;
import com.doraemon.dto.EmployeeLoginDTO;
import com.doraemon.dto.EmployeePageQueryDTO;
import com.doraemon.entity.Employee;
import com.doraemon.properties.JwtProperties;
import com.doraemon.result.PageResult;
import com.doraemon.result.Result;
import com.doraemon.service.EmployeeService;
import com.doraemon.utils.JwtUtil;
import com.doraemon.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理Controller
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService; // 注入员工Service层
    @Autowired
    private JwtProperties jwtProperties; // 注入JWT配置属性

    /***
     * 员工登陆
     * ---
     * @param employeeLoginDTO 员工登录DTO类（前端参数）
     * @return: com.doraemon.result.Result<com.doraemon.vo.EmployeeLoginVO>
     */
    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) { // 封装员工登陆DTO类
        log.info("员工登录：{}", employeeLoginDTO);

        // 调用Service层 login 方法，获取查询到的员工实体
        Employee employee = employeeService.login(employeeLoginDTO);

        // 登录成功后，生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());  // 以 键值对形式 添加员工ID到JWT载荷中
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),  // 使用配置中的密钥
                jwtProperties.getAdminTtl(),  // 使用配置中的过期时间
                claims);  // 添加载荷

        // 构建员工登录VO类
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build(); // 通过@Builder注解，构建EmployeeLoginVO对象

        return Result.success(employeeLoginVO);  // 返回登录成功结果
    }

    /***
     * 退出登陆
     * ---
     * @return: com.doraemon.result.Result<java.lang.String>
     */
    @PostMapping("/logout")
    @ApiOperation("员工退出")
    public Result<String> logout() {
        log.info("员工退出");

        return Result.success();
    }

    /***
     * 新增员工
     * ---
     * @param employeeDTO 员工DTO类（前端参数）
     * @return: com.doraemon.result.Result<java.lang.String>
     */
    @PostMapping()
    @ApiOperation("新增员工")
    public Result<String> addEmployee(@RequestBody EmployeeDTO employeeDTO) {
        log.info("新增员工：{}", employeeDTO);

        // 调用Service层 save 方法，新增员工
        employeeService.save(employeeDTO);

        return Result.success();
    }

    /***
     * 修改员工账号状态
     * ---
     * @param status 员工账号状态 0 禁用 1 启用
     * @param id 员工id
     * @return: com.doraemon.result.Result<java.lang.String>
     */
    @PostMapping("/status/{status}")
    @ApiOperation("修改员工账号状态")
    public Result<String> updateStatus(@PathVariable Integer status, @RequestParam Long id) {
        if (status == 1) {
            log.info("员工账号状态修改：ID={}，状态=已启用", id);
        } else log.info("员工账号状态修改：ID={}，状态=已禁用", id);

        // 调用Service层 updateStatus 方法，修改员工账号状态
        employeeService.updateStatus(status, id);

        return Result.success();
    }

    /***
     * 编辑员工
     * ---
     * @param employeeDTO 员工DTO类（前端参数）
     * @return: com.doraemon.result.Result<java.lang.String>
     */
    @PutMapping()
    @ApiOperation("编辑员工")
    public Result<String> updateEmployee(@RequestBody EmployeeDTO employeeDTO) {
        log.info("编辑员工：{}", employeeDTO.getId());

        // 调用Service层 updateEmployee 方法，编辑员工
        employeeService.updateEmployee(employeeDTO);

        return Result.success();
    }

    /***
     * 根据id查询员工
     * ---
     * @param id 员工id
     * @return: com.doraemon.result.Result<com.doraemon.entity.Employee> 员工实体
     */
    @GetMapping("{id}")
    @ApiOperation("根据id查询员工")
    public Result<Employee> findById(@PathVariable Long id) { // 路径传参，接收id
        log.info("查询员工：{}", id);

        // 调用Service层 getById 方法，获取查询到的员工实体
        Employee employee = employeeService.getById(id);

        return Result.success(employee);
    }

    /***
     * 分页查询
     * ---
     * @param employeePageQueryDTO 员工分页DTO类（前端参数）
     * @return: com.doraemon.result.Result<java.util.List < com.doraemon.dto.EmployeeDTO>>
     */
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO) { // 封装员工分页DTO类（Get请求可以不用@RequestBody接收）
        log.info("员工分页查询：页码 {},每页展示 {},姓名 {}", employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize(), employeePageQueryDTO.getName());

        // 调用Service层 pageQuery 方法，获取查询到的分页结果集对象pageResult
        PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO);

        return Result.success(pageResult);
    }

}